import asyncio

a = 0


async def handle_socket(reader, writer):
    global a
    buffer = b''
    while True:
        data = await reader.read(128)
        buffer += data
        start_of_image = buffer.find(b'\xff\xd8')
        end_of_image = buffer.find(b'\xff\xd9\r\n')
        if start_of_image != -1 and end_of_image != -1:
            image_data = buffer[start_of_image:end_of_image + 2]  # 提取图像数据
            a = a + 1
            name = str(a) + ".jpg"
            with open(name, "wb") as f:
                f.write(image_data)
            buffer = buffer[end_of_image + 4:]  # 从数据流中移除已处理的图像数据
        # else:
        #     continue  # 如果找不到完整的图像数据，则退出内层循环


async def main():
    server = await asyncio.start_server(handle_socket, '192.168.90.164', 18080)

    async with server:
        await server.serve_forever()


if __name__ == '__main__':
    asyncio.run(main())
